package com.xj.nrpc.server;

import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.xj.nrpc.core.constant.Constants;
import com.xj.nrpc.handler.ServerChannelHandler;
import com.xj.nrpc.zk.ZookeeperFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

@Component
public class NRPCServer implements ApplicationListener<ContextRefreshedEvent> {
	public void start() {
		int port = 8080;
		int weight=2;
		ServerBootstrap serverBootStrap = new ServerBootstrap();
		EventLoopGroup parentGroup = new NioEventLoopGroup();
		EventLoopGroup childGroup = new NioEventLoopGroup();

		serverBootStrap.channel(NioServerSocketChannel.class);
		serverBootStrap.group(parentGroup, childGroup);
		serverBootStrap.option(NioChannelOption.SO_BACKLOG, 128).childOption(NioChannelOption.SO_KEEPALIVE, false)
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(
								new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
						ch.pipeline().addLast(new StringDecoder());
						ch.pipeline().addLast(new IdleStateHandler(60, 45, 20, TimeUnit.SECONDS));
						ch.pipeline().addLast(new ServerChannelHandler());
						ch.pipeline().addLast(new StringEncoder());
					}
				});
		try {
			ChannelFuture cf = serverBootStrap.bind(port).sync();

			CuratorFramework curator = ZookeeperFactory.create();
			InetAddress netAddress = InetAddress.getLocalHost();

			curator.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(
					Constants.SERVER_PATH + "/" + netAddress.getHostAddress() + "#" + port + "#" + weight + "#");
			cf.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				parentGroup.shutdownGracefully().sync();
				childGroup.shutdownGracefully().sync();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		this.start();

	}
}
